# coding=utf-8
"""

Tomato beta 1.0

author: weelion
email: weelion@qq.com

"""
import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.uic import *
import threading
import time
import urllib

reload(sys)
sys.setdefaultencoding('utf8')

PER_TOMATO       = 25
PER_REST         = 5
COUNT_TOMATO     = 3
LONG_REST        = 15
COUNT            = 0
IS_TOMATO        = 1
URL              = 'http://doo.dev.com/tomato.php'
MARK             = u"写点东西吧"
PROPERTY         = {}

# 主程序
class TomatoMain(QMainWindow):
    def __init__(self):
        global PER_TOMATO, PER_REST, COUNT_TOMATO, LONG_REST, URL, MARK, PROPERTY
        super(TomatoMain, self).__init__()
        loadUi("ui/main.ui", self)

        PROPERTY['Title'] = "Tomato beta 1.0"
        PROPERTY['Icon']  = QIcon("icon.png")
        self.setWindowTitle(PROPERTY['Title'])
        self.setWindowIcon(PROPERTY['Icon'])

        # 按鈕事件
        self.connect(self.start, SIGNAL('clicked()'), self.Start)
        self.connect(self.reset, SIGNAL('clicked()'), self.Reset)
        self.connect(self.stop, SIGNAL('clicked()'), self.Stop)
        self.reset.setEnabled(False)
        self.stop.setEnabled(False)

        # 初始化配置
        self.showTime.display('00:00')
        self.perTomato.setValue(PER_TOMATO) 
        self.perTomato.setSingleStep(1)
        self.perTomato.setMinimum(1)
        self.perRest.setValue(PER_REST)
        self.perRest.setSingleStep(1)
        self.perRest.setMinimum(1)
        self.countTomato.setValue(COUNT_TOMATO)
        self.countTomato.setSingleStep(1)
        self.countTomato.setMinimum(1)
        self.longRest.setValue(LONG_REST)
        self.longRest.setSingleStep(5)
        self.longRest.setMinimum(5)
        self.api.setText(URL)
        self.mark.setText(MARK)

        # 托盘
        Tray = QSystemTrayIcon(PROPERTY['Icon'], self)
        Tray.setToolTip(PROPERTY['Title'])
        Tray.activated.connect(self.TrayClick)
        Tray.setContextMenu(self.TrayMenu(Tray))
        Tray.show()

    def hideEvent(self, event):
        self.hidden = True
        self.setWindowFlags(Qt.ToolTip)
        self.setVisible(False)

    def showEvent(self, event):
        self.hidden = False
        self.setVisible(True)

    def TrayMenu(self, tray):
        trayMenu = QMenu()
        action = QAction(u"关于", tray)
        action.triggered.connect(self.About)
        trayMenu.addAction(action)
        action = QAction(u"退出", tray)
        action.triggered.connect(QApplication.instance().quit)
        trayMenu.addAction(action)
        return trayMenu

    def TrayClick(self, reason):
        # 左键单击
        if reason == 3:
            self.setWindowFlags(Qt.Window)
            self.show()
            self.setWindowState(self.windowState() & ~Qt.WindowMinimized | Qt.WindowActive)
            self.activateWindow()

    def About(self):
        msgBox = QMessageBox(self)
        msgBox.setMinimumWidth(3000)
        msgBox.setWindowTitle(u"关于")
        msgBox.setText(u"作者：weelion");
        msgBox.setInformativeText(u'邮箱：weelion@qq.com')
        msgBox.exec_()

    def Start(self):
        global PER_TOMATO, PER_REST, COUNT_TOMATO, LONG_REST, IS_TOMATO, COUNT

        PER_TOMATO = self.perTomato.value()
        PER_REST = self.perRest.value()
        COUNT_TOMATO = self.countTomato.value()
        LONG_REST = self.longRest.value()
        IS_TOMATO = 1
        COUNT = 0

        # 开启线程
        self.Timer = TimerThread(self.showTime, self.mark)
        self.Timer.start()
        
        self.start.setEnabled(False)
        self.reset.setEnabled(True)
        self.stop.setEnabled(True)

    def Reset(self):
        self.Timer.stopMe()
        self.Start()

    def Stop(self):
        self.Timer.stopMe()
        self.start.setEnabled(True)
        self.reset.setEnabled(False)
        self.stop.setEnabled(False)

# 计时线程
class TimerThread(threading.Thread):
    def __init__(self, show, mark):
        self.keepRunning = 1
        self.show = show
        self.mark = mark
        threading.Thread.__init__(self)

    def run(self):
        global PER_TOMATO, PER_REST, COUNT_TOMATO, LONG_REST, COUNT, IS_TOMATO, URL
        while self.keepRunning:
            if IS_TOMATO:
                IS_TOMATO = 0
                total = PER_TOMATO * 60 # 总时间
                self.show.setStyleSheet("color: rgb(204, 0, 0)")
                self.loop(total)
                post = Post(URL, self.mark.text())
                post.start()
                COUNT += 1
            else:
                IS_TOMATO = 1
                self.show.setStyleSheet("color: rgb(0, 102, 204)")

                if COUNT_TOMATO == COUNT:
                    total = LONG_REST * 60
                    self.loop(total)
                    COUNT = 0
                else:
                    total = PER_REST * 60
                    self.loop(total)


    def loop(self, total):
        while total > 0 and self.keepRunning:
            minute = total/60  # 分钟
            second = total%60  # 秒
            total -= 1
            self.show.display(str(minute) + ':' + '%02d'%second)
            time.sleep(1)

    def stopMe(self):
        self.show.setStyleSheet("color: rgb(0, 0, 0)")
        self.show.display('00:00')
        self.keepRunning = 0

# 数据提交线程
class Post(threading.Thread):
    def __init__(self, url, mark):
        self.url = url
        self.mark = mark
        threading.Thread.__init__(self)

    def run(self):
        params = urllib.urlencode({'tomato':1, 'time':int(time.time()), 'mark':self.mark})
        f = urllib.urlopen(self.url + "?%s"%params)
        f.read()

if __name__ == "__main__":
    app = QApplication(sys.argv)
    tomato = TomatoMain()
    tomato.show()
    app.exec_()
